package com.ktjy.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;

/**
 * MQ连接工具类
 */
public class RabbitMQUtil {

    // RabbitMQ 连接信息
    public static final String HOST = "110.41.18.202";
    public static final int PORT = 5672;
    public static final String VHOST = "/t382";// 虚拟主机
    public static final String USERNAME = "ktjiaoyu"; // 用户名
    public static final String PASSWORD = "123456"; // 密码
    // 连接工厂对象
    private static final ConnectionFactory factory = new ConnectionFactory();

    static {
        // 设置连接信息
        factory.setHost(HOST);
        factory.setPort(PORT);
        factory.setVirtualHost(VHOST);
        factory.setUsername(USERNAME);
        factory.setPassword(PASSWORD);
    }

    /**
     * 获取新连接
     */
    public static Connection newConnection() throws IOException {
        try {
            return factory.newConnection();
        } catch (Exception e) {
            e.printStackTrace();
            // 不能隐瞒异常
            throw new IOException(e);
        }
    }

    /**
     * 关闭信道
     */
    public static void close(Channel channel) {
        if (channel != null) {
            try {
                channel.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭连接
     */
    public static void close(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
